//
//  LKElearningKaoshiViewController.m
//  YLHelper
//
//  Created by she1323 on 2018/6/26.
//  Copyright © 2018年 she1323. All rights reserved.
//

#import "LKElearningKaoshiViewController.h"
#import "LKTestCell.h"
#import "LKVideoTestModel.h"
#import "LKTestpageNameViewController.h"
#import "LKVideoKaoshiModel.h"
@interface LKElearningKaoshiViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>{
    NSInteger _secondnumber;
    NSInteger _minutenumber;
}
@property(nonatomic,strong)UICollectionView *collectionView;
@property(nonatomic,strong)UICollectionViewFlowLayout *flowLayout;
@property(nonatomic,strong)NSTimer *timer;
@property(nonatomic,strong)LKBaseLabel *timelabel;
@property(nonatomic,strong)NSMutableArray *datalistArray;
@property(nonatomic,assign)NSInteger currentIndex;
@property(nonatomic,strong)NSMutableArray *selectsArray;
@property(nonatomic,strong)UIButton *btn;
@property(nonatomic,copy)NSString *paperName;
@property(nonatomic,assign)NSInteger kaoshiTime;
@end

@implementation LKElearningKaoshiViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.currentIndex = 0;
    _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(mytimer) userInfo:nil repeats:YES];
    [_timer setFireDate:[NSDate distantFuture]];
    [self setcollectionView];
    [self getExaminationPaperData];
    // Do any additional setup after loading the view.
}
-(void)mytimer{
    if (_secondnumber == 0) {
        _secondnumber = 59;
        _minutenumber --;
        if (_minutenumber < 0) {
            [self commitTestAnser];
            [_timer invalidate];
            _timer = nil;
            return;
        }
    }
    _secondnumber --;
    _timelabel.text = [NSString stringWithFormat:@"%02ld:%02ld",_minutenumber,_secondnumber];
}
-(void)setNavgationBackBtn{
    [super setNavgationBackBtn];
    self.btn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.btn.size = CGSizeMake(80, 44);
    _btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    _btn.titleLabel.font = [UIFont systemFontOfSize:16];
    [_btn setTitle:@"确定" forState:UIControlStateNormal];
    [_btn setTitle:@"下一题" forState:UIControlStateSelected];
    [_btn setTitleColor:blueDefault forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.btn];
    [_btn addTarget:self action:@selector(sureAnswerOrNext:) forControlEvents:UIControlEventTouchUpInside];
    _timelabel = [LKBaseLabel labelWithFrame:CGRectMake(0, 0, 150, 40) text:[NSString stringWithFormat:@"%02ld:%02ld",_minutenumber,_secondnumber] textColor:ColorRGB(0, 0, 0) font:[UIFont systemFontOfSize:16] textAlignment:NSTextAlignmentCenter backgroundColor:[UIColor clearColor]];
    self.navigationItem.titleView = _timelabel;
    [self.backButton addTarget:self action:@selector(chooseExitTest:) forControlEvents:UIControlEventTouchDownRepeat];
}
-(void)chooseExitTest:(UIButton *)btn{
    WS(weakSelf)
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"您是否要交卷?" message:nil preferredStyle:UIAlertControllerStyleAlert];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"否" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"是" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf commitTestAnser];
    }]];
    [self presentViewController:alert animated:YES completion:nil];
    
}
-(void)back{
    WS(weakSelf)
    self.currentIndex = self.collectionView.contentOffset.x / WIDTH;
    if (self.currentIndex == 0) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"您是否要提交试卷?" message:nil preferredStyle:UIAlertControllerStyleAlert];
        
        [alert addAction:[UIAlertAction actionWithTitle:@"否" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }]];
        [alert addAction:[UIAlertAction actionWithTitle:@"是" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [weakSelf commitTestAnser];
        }]];
        [self presentViewController:alert animated:YES completion:nil];
        return;
    }
    _btn.selected = YES;
    [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:self.currentIndex - 1 inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
    
//    LKTestCell *cell = (LKTestCell *)[self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:self.currentIndex - 1  inSection:0]];
//    cell.model.hadSureAns = YES;
//    cell.sureAnswer = YES;
//    [cell.tableView reloadData];
//    NSLog(@"%@",cell.selectValue);
}
/**
 确定答案
 
 */
-(void)sureAnswerOrNext:(UIButton *)btn{
    if ([btn.titleLabel.text isEqual:@"交卷"]) {
        [self commitTestAnser];
        return;
    }
    self.currentIndex = self.collectionView.contentOffset.x / WIDTH;
    if (self.selectsArray.count < self.currentIndex) {
        btn.selected = YES;
    }
    LKTestCell *cell = (LKTestCell *)[self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:self.currentIndex  inSection:0]];
    if (!btn.selected) {
        cell.kaoshiModel.hadSureKaoshiAnswer = YES;
        [cell.tableView reloadData];
        NSMutableArray *anserArr = [[NSMutableArray alloc] init];
        for (NSInteger i = 0; i < cell.selectValue.length; i++) {
            char chara = [cell.selectValue characterAtIndex:i];
            NSString *chartStr = [NSString stringWithFormat:@"%c",chara];
            [anserArr addObject:chartStr];
        }
        NSDictionary *selectDic = [NSDictionary dictionaryWithObjectsAndKeys:anserArr,@"QuestionAnswerName",cell.kaoshiModel.questionBankId,@"QuestionId", nil];
        [self.selectsArray addObject:selectDic];
        if ([[[cell.numberLabel.text componentsSeparatedByString:@"/"] firstObject] isEqual:[[cell.numberLabel.text componentsSeparatedByString:@"/"] lastObject]]) {
            [_btn setTitle:@"交卷" forState:UIControlStateNormal];
            return;
        }
        
    }else{
        [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:self.currentIndex + 1 inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
    }
    
    btn.selected = !btn.selected;
}
/**
 提交考试答案
 */
-(void)commitTestAnser{
    NSMutableDictionary *mutabDic = [[NSMutableDictionary alloc] init];
    NSDictionary *param;
    NSString *url;
    url = submitKaoshiUrl;
    NSInteger expandTime = _kaoshiTime * 60 - (_minutenumber * 60 + _secondnumber);
    NSString *expandTimeStr = [NSString stringWithFormat:@"%ld",expandTime];
    NSString *expendMinute = [self getMMSSFromSS:expandTimeStr];
    param = [NSDictionary dictionaryWithObjectsAndKeys:self.appointId,@"ExaminationAppointId",expendMinute,@"ExpendMinute", nil];
    NSDictionary *param1 = [NSDictionary dictionaryWithObjectsAndKeys:self.selectsArray,@"AnswerInput", nil];
    [mutabDic addEntriesFromDictionary:param];
    [mutabDic addEntriesFromDictionary:param1];
    [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerlUrl apiPath:url header:[LKUserInforTool header] parameters:mutabDic progress:^(NSProgress * _Nullable progress) {
        
    } success:^(BOOL isSuccess, id  _Nullable responseObject) {
        LKTestpageNameViewController *vc = [[LKTestpageNameViewController alloc] init];
        vc.isKaoshi = YES;
        vc.paperId = self.appointId;
        vc.paperName = self.paperName;
//        k
        [self.navigationController pushViewController:vc animated:YES];
    } failure:^(NSString * _Nullable errorMessage) {
        
    }];
}
//传入 秒  得到  xx分钟xx秒
-(NSString *)getMMSSFromSS:(NSString *)totalTime{
    
    NSInteger seconds = [totalTime integerValue];
    
    //format of minute
    NSString *str_minute = [NSString stringWithFormat:@"%02ld",seconds/60];
    //format of second
    NSString *str_second = [NSString stringWithFormat:@"%02ld",seconds%60];
    //format of time
    NSString *format_time = [NSString stringWithFormat:@"%@:%@",str_minute,str_second];
    
    NSLog(@"format_time : %@",format_time);
    
    return format_time;
    
}
/**
 设置collectionview
 */
-(void)setcollectionView{
    self.flowLayout = [[UICollectionViewFlowLayout alloc] init];
    self.flowLayout.itemSize = CGSizeMake(WIDTH, HEIGHT - NAVIGATION_BAR_HEIGHT);
    self.flowLayout.minimumLineSpacing = 0;
    self.flowLayout.minimumInteritemSpacing = 0;
    self.flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, NAVIGATION_BAR_HEIGHT ,WIDTH, HEIGHT - NAVIGATION_BAR_HEIGHT) collectionViewLayout:self.flowLayout];
    _collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.panGestureRecognizer.enabled = NO;
    for (NSInteger i = 0; i < self.collectionView.gestureRecognizers.count; i++) {
        UIGestureRecognizer *ges = self.collectionView.gestureRecognizers[i];
        [self.collectionView removeGestureRecognizer:ges];
    }
    [self.view addSubview:self.collectionView];
    self.collectionView.pagingEnabled = YES;
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    self.collectionView.scrollEnabled = NO;
    self.collectionView.showsVerticalScrollIndicator = NO;
    [self.collectionView registerNib:[UINib nibWithNibName:@"LKTestCell" bundle:nil] forCellWithReuseIdentifier:@"LKTestCell"];
    [self.collectionView reloadData];
}
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.datalistArray.count;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    LKTestCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"LKTestCell" forIndexPath:indexPath];
    cell.isKaoshi = YES;
    cell.kaoshiModel = self.datalistArray[indexPath.row];
    cell.numberLabel.text = [NSString stringWithFormat:@"%ld/%ld",indexPath.row + 1,self.datalistArray.count];
    return cell;
    
}

/**
 获取考试的习题
 */
-(void)getExaminationPaperData{
    NSString *url = startKaoshiUrl;
    [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerlUrl apiPath:url header:[LKUserInforTool header] parameters:@{@"Id":self.appointId} progress:^(NSProgress * _Nullable progress) {
        
    } success:^(BOOL isSuccess, id  _Nullable responseObject) {
        NSDictionary *dic = responseObject[@"result"];
        LKVideoKaoshiModel *model = [LKVideoKaoshiModel modelWithDictionary:dic];
        self.paperName = model.examinationAppoint.examinationPaperName;
        _secondnumber = 0;
        _minutenumber = [model.examinationAppoint.needMinute integerValue];
        _kaoshiTime = [model.examinationAppoint.needMinute integerValue];
        [self.datalistArray addObjectsFromArray:model.questionBank];
        [self.collectionView reloadData];
        [_timer setFireDate:[NSDate distantPast]];
    } failure:^(NSString * _Nullable errorMessage) {
        
    }];
}
-(void)dealloc{
    [_timer invalidate];
    _timer = nil;
}
-(NSMutableArray *)datalistArray{
    if (!_datalistArray) {
        _datalistArray = [[NSMutableArray alloc] init];
    }
    return _datalistArray;
}
-(NSMutableArray *)selectsArray{
    if (!_selectsArray) {
        _selectsArray = [[NSMutableArray alloc] init];
    }
    return _selectsArray;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
